#include "maininterfacewidget.h"
#include "ui_maininterfacewidget.h"
#include "user.h"
#include "addfriendsender.h"
#include "addfriendreceiver.h"
#include "addfriendsearch.h"
#include "friendlist.h"


void MainInterfaceWidget::closeEvent(QCloseEvent *)
{
    emit this->closeMainInterfaceWidget();
}

void MainInterfaceWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        on_btn_send_main_clicked(); // 模拟发送按钮被点击的事件
    }
}

MainInterfaceWidget::MainInterfaceWidget(QWidget *parent, user userSelf, QString friendName, int friendId, QString friendPhoto, QWebSocket* socket)
    : QWidget(parent)
    , ui(new Ui::MainInterfaceWidget)
{
    ui->setupUi(this);
    //websocket传输代码
    this->userSelf = userSelf;
    this->userSelf.setUserName(userSelf.getUserName());
    this->friendName = friendName;
    this->friendId = friendId;
    this->friendPhoto = friendPhoto;
   //创建socket
    this->socket=socket;
    ui->dialogTextBrowser->setOpenLinks(true);
    ui->dialogTextBrowser->setOpenExternalLinks(true);


    //每次打开maininterface时
    //遍历消息队列
    for(int i = 0; i < messageQueue.size(); i++)
    {
        //拉取的信息需要和打开的好友窗口是同一人
        if((messageQueue[i].receiverId == this->userSelf.getUserId().toInt())&&(messageQueue[i].senderId == this->friendId))
        {

            ui->dialogTextBrowser->append(returnImageHtml(messageQueue[i].senderPhoto) + messageQueue[i].getTimeAndSender());
            ui->dialogTextBrowser->append(messageQueue[i].getMessageContent());//对话框中添加信息
            //对话双方均在线直接显示
        }
        //拉取的信息是自己发的消息且消息接收者是窗口打开的好友
        if((messageQueue[i].receiverId == this->friendId)&&(messageQueue[i].senderId == this->userSelf.getUserId().toInt()))
        {
            ui->dialogTextBrowser->append(returnImageHtml(messageQueue[i].senderPhoto) + messageQueue[i].messageTime+" me:");
            ui->dialogTextBrowser->append(messageQueue[i].getMessageContent());//对话框中添加信息
            //对话双方均在线直接显示
        }
    }

    //打开界面后如果收到消息
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
    {
        //qDebug() << "Received message:" << message;
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
         qDebug() << obj ;
        //类型为chat
        if (type == "chat")
        {
            QVariantMap messageMap = obj.toVariantMap();
            QMap senderMap = messageMap.value("sender").toMap();
            QVariant senderName = senderMap.value("username");
            QVariant senderId = senderMap.value("id");
            QVariant senderPhoto = senderMap.value("photo");
            QString receivedContent = obj.value("content").toString();
            QString receivedTime = obj.value("time").toString();
            //接收到信息
            Message chatMessage{this->userSelf.getUserName(), this->userSelf.getUserId().toInt(),this->userSelf.getUserPhoto(), receivedTime, senderName.toString(), senderId.toInt(), senderPhoto.toString(), receivedContent};
            //messageQueue.append(chatMessage);
            if(senderId.toInt() == this->friendId)//打开的窗口和发信息的好友需是同一人
            {
                //下面开始打印信息
                ui->dialogTextBrowser->append(returnImageHtml(chatMessage.senderPhoto) + chatMessage.getTimeAndSender());
                ui->dialogTextBrowser->append(chatMessage.getMessageContent());

            }

        }
    });

    //绑定回车按键
    connect(ui->messageSendTextEdit, SIGNAL(returnPressed()), this, SLOT(on_btn_send_main_clicked()));
}

MainInterfaceWidget::~MainInterfaceWidget()
{
    delete ui;
}

//发送信息
void MainInterfaceWidget::on_btn_send_main_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        userSelf.getUserPhoto(),//photo
        userSelf.getUserGender()//gender
    };
    QDateTime currentTime = QDateTime::currentDateTime(); // 获取当前时间
    int year = currentTime.date().year(); // 获取年份
    int month = currentTime.date().month(); // 获取月份
    int day = currentTime.date().day();     // 获取日期
    int hour = currentTime.time().hour();   // 获取小时
    int minute = currentTime.time().minute(); // 获取分钟
    //设定时间格式
    QString time = QString::number(year) + "-" + QString::number(month) + "-"
            + QString::number(day) + " " + QString::number(hour) + ":" + QString::number(minute);
    //get content
    QString sendContent = ui->messageSendTextEdit->toPlainText();//传输服务器


    //connect to server
    //sender信息
    QJsonObject senderValue
    {
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", Sender.photo},
        {"gender", Sender.gender.toInt()}
    };
    //receiver信息
    QJsonObject receiverValue
    {
        {"id", friendId},
        {"username", ""},
        {"photo", ""},
        {"gender", 1}
    };
    //发送的信息
    QJsonObject json{
        {"sender",senderValue},
        {"receiver", receiverValue},
        {"time", time},
        {"type", "chat"},
        {"content", sendContent},
        {"is_photo","0"}
    };
    QJsonDocument doc(json);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    this->socket->sendTextMessage(data);
    Message myMessage {this->friendName, friendId, friendPhoto, time, " me:", this->userSelf.getUserId().toInt(), this->userSelf.getUserPhoto(), sendContent};
    messageQueue.append(myMessage);

    ui->dialogTextBrowser->append(returnImageHtml(myMessage.senderPhoto) + time + " me:");
    ui->dialogTextBrowser->append("<font color = 'black' size = 24px>" + sendContent + "</font>");
    ui->messageSendTextEdit->clear();
}

//清空打字框
void MainInterfaceWidget::on_btn_clear_main_clicked()
{
    ui->messageSendTextEdit->clear();
}

//获取历史消息
void MainInterfaceWidget::on_btn_getHistoryMessage_clicked()
{
    QString resourcePath = ":/asset/config/config.json";
    QFile jsonFile(resourcePath);
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    QByteArray jsonData = jsonFile.readAll();
    // 将 JSON 数据转换为 QVariant 对象
    QJsonParseError error;
    QJsonObject result = QJsonDocument::fromJson(jsonData, &error).object();
    QJsonObject jsonUrl = QJsonDocument::fromJson(jsonData).object();
    qDebug() << "url :" << jsonUrl;
    jsonFile.close();
    QVariantMap urlVariantMap = jsonUrl.toVariantMap();
    QMap urlMap = urlVariantMap.value("server").toMap();
    host = urlMap.value("host").toString();
    port = urlMap.value("port").toString();
    }
    //connect to server
    QNetworkRequest request(QUrl("http://"+host+':'+port+"/slimarveous/get_history"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json.insert("id", this->userSelf.getUserId().toInt());
    json.insert("token", this->userSelf.getUserPassword());
    json.insert("the_other_id", this->friendId);
    json.insert("start", 0);
    qDebug()<<json;
    QJsonDocument doc(json);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    QNetworkReply *reply = manager.post(request, data);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        qDebug() << "请求结果" ;
        if (reply->error() == QNetworkReply::NoError)
        {
            // 读取响应数据
            QByteArray dataReply = reply->readAll();
           // qDebug()<<dataReply;
            // 将 JSON 数据转换为 QVariant 对象
            QJsonParseError error;
            QJsonObject result = QJsonDocument::fromJson(dataReply, &error).object();
            // 处理 JSON 数据
            if (error.error == QJsonParseError::NoError)
            {
                QVariantMap resultMap = result.toVariantMap();
                //提取状态码
                QVariant status_code = resultMap.value("status_code");
                status_code.toString();
                //将未读消息json文件转化成map

                //解析历史消息数组
                QJsonArray hisMsg = resultMap.value("history").toJsonArray();
                for(int i = 0 ; i < hisMsg.size(); i++)
                {
                    QJsonObject hisJsonObj = hisMsg.at(i).toObject();
                    QVariantMap messageMap = hisJsonObj.toVariantMap();
                    //sender
                    QMap senderMap = messageMap.value("sender").toMap();
                    QVariant senderName = senderMap.value("username");
                    int senderId = senderMap.value("id").toInt();
                    QVariant senderPhoto = senderMap.value("photo");
                    //receiver
                    QMap receiverMap = messageMap.value("receiver").toMap();
                    QVariant receiverName = receiverMap.value("username");
                    int receiverId = receiverMap.value("id").toInt();
                    QVariant receiverPhoto = receiverMap.value("photo");
                    //content and time
                    QString hisMsgContent = hisJsonObj.value("content").toString();
                    QString hisMsgTime = hisJsonObj.value("time").toString();
                    //创建Message结构体
                    Message hisMessage{receiverName.toString(), receiverId, receiverPhoto.toString(), hisMsgTime, senderName.toString(), senderId, senderPhoto.toString(), hisMsgContent};
                    historyMessage.append(hisMessage);
                }

                //打印历史信息
                for(int i = (historyMessage.size() - 1); i >= 0 ; i--)
                {
                    //拉取的信息需要和打开的好友窗口是同一人
                    if((historyMessage[i].receiverId == this->userSelf.getUserId().toInt())&&(historyMessage[i].senderId == this->friendId))
                    {
                        ui->dialogTextBrowser->append(returnImageHtml(historyMessage[i].senderPhoto) + historyMessage[i].getTimeAndSender());
                        ui->dialogTextBrowser->append(historyMessage[i].getMessageContent());//对话框中添加信息
                    }
                    //拉取的信息是自己发的消息且消息接收者是窗口打开的好友
                    if((historyMessage[i].receiverId == this->friendId)&&(historyMessage[i].senderId == this->userSelf.getUserId().toInt()))
                    {
                        ui->dialogTextBrowser->append(returnImageHtml(historyMessage[i].senderPhoto) + historyMessage[i].messageTime+" me:");
                        ui->dialogTextBrowser->append(historyMessage[i].getMessageContent());//对话框中添加信息
                    }
                }
            }
        }
        else
        {
            qDebug()<<"error";
            // 释放资源
            reply->deleteLater();
        }
    });
}

QString MainInterfaceWidget::returnImageHtml(QString imageHtmlString)
{
    QUrl imageUrl(imageHtmlString);
    QNetworkAccessManager networkManager;
    QNetworkReply *reply = networkManager.get(QNetworkRequest(imageUrl));
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    QByteArray imageData = reply->readAll();
    reply->deleteLater();

    // 将图片数据转换为 base64 编码
    QString base64Image = QString::fromLatin1(imageData.toBase64());

    // 在 QTextBrowser 中插入 img 标签
    QString imgHtml = QString("<img src='data:image/jpg;base64,%1' width='50' height='50'  />").arg(base64Image);
    return imgHtml;
}
